import * as JSZip from 'jszip'

export default class jszipHelper {
    private _dataMap: Map<string, any> = new Map()

    private _zip: JSZip = null

    init(url: string, cb: Function) {

        url = cc.url.raw(url)
        cc.loader.load({ url: url, type: "binary" }, (err, bin: cc.BufferAsset) => {
            JSZip.loadAsync(bin).then((v) => {
                this._zip = v
                cb()
            })
        })
        //
        //使用bundle的load不行
    }

    load(url: string, type: cc.SpriteFrame | cc.VideoClip | cc.JsonAsset |
        any, cb: Function) {
        if (this._zip == null) {
            cc.error('压缩包没有正确获取')
            return
        }
        let data = this._dataMap.get(url)
        if (data) {
            cb(data)
            return
        }

        switch (type) {
            case cc.SpriteFrame:
                this._zip.file(url).async('blob').then((data: any) => {
                    let endStr = '.' + url.split(".").pop()
                    cc.assetManager.parser.parse(url, data, endStr, {
                        __flipY__: false,
                        __premultiplyAlpha__: false
                    }, (err, img: ImageBitmap) => {
                        let texture = new cc.Texture2D()
                        //@ts-ignore
                        texture.initWithData(img, cc.Texture2D.PixelFormat.RGBA8888, img.width, img.height)
                        let spF = new cc.SpriteFrame()
                        spF.setTexture(texture)
                        this._dataMap.set(url, spF)
                        cb(spF)
                    })
                })
                break
            case cc.VideoClip:
                this._zip.file(url).async('blob').then((data: any) => {
                    let objectUrl = window.URL.createObjectURL(data)
                    this._dataMap.set(url, objectUrl)
                    cb(objectUrl)
                })
                break
            case cc.JsonAsset:
                this._zip.file(url).async('text').then((data: any) => {
                    let json = JSON.parse(data)
                    this._dataMap.set(url, json)
                    cb(json)
                })
                break
        }
    }
}
